package com.hairline.shiro;

import com.hairline.bean.User;
import com.hairline.bean.UserExample;
import com.hairline.mapper.UserMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class WxRealm extends AuthorizingRealm {
    @Autowired
    UserMapper userMapper;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        MallToken mallToken = (MallToken) authenticationToken;

        //根据type不同,用不同的方式处理username
        String username = mallToken.getUsername();
        AuthenticationInfo info = getInfo(username);
        return info;
    }

    private AuthenticationInfo getInfo(String username) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameEqualTo(username);
        List<User> users = userMapper.selectByExample(userExample);
        String password = users.get(0).getPassword();

        //传入 username,查询到的 密码  ,以及 this.getName
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(users.get(0), password, this.getName());
        return simpleAuthenticationInfo;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) principalCollection.getPrimaryPrincipal();
        //使用mapper获取权限list
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameEqualTo(username);
        List<User> users = userMapper.selectByExample(userExample);
        Byte userLevel = users.get(0).getUserLevel();

        //权限的list传给sim
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        //

        simpleAuthorizationInfo.addStringPermission(userLevel.toString());
        return simpleAuthorizationInfo;

    }


}
